<template>
  <div class="data-ranking">
    <div class="controls">
      <el-tabs v-model="activeTab" class="custom-tabs">
        <el-tab-pane class="tab_pane" label="当天用电量排行" name="daily"></el-tab-pane>
        <el-tab-pane label="周用电量排行" name="weekly"></el-tab-pane>
        <el-tab-pane label="月用电量排行" name="monthly"></el-tab-pane>
      </el-tabs>
    </div>
    <div class="content-row">
      <div class="ranking-chart" v-if="noData ||filteredRankingData.length">
        <div class="filter-controls">
          <el-select v-model="selectedMoldCode" placeholder="选择设备类型" @change="filterData" class="custom-select">
            <el-option value="" label="所有设备"></el-option>
            <el-option
              v-for="(count, code) in deviceTypeCounts"
              :key="code"
              :label="'类型 ' + code + ' (' + count + ')'"
              :value="code"
            ></el-option>
          </el-select>
        </div>
        <div class="ranking-list">
          <table>
            <thead>
              <tr>
                <th>设备</th>
                <th>用电量</th>
              </tr>
            </thead>
            <tbody v-if="filteredRankingData.length">
              <tr v-for="(item, index) in filteredRankingData" :key="index">
                <td class="probe-name">{{ item.probe_name }}</td>
                <td class="quantity">{{ item.total_ele_quantity }} 度</td>
              </tr>
            </tbody>
            <tbody v-else>
              <!-- 当没有数据时，显示占位符 -->
              <tr v-for="n in 5" :key="n">
                <td class="probe-name skeleton"></td>
                <td class="quantity skeleton"></td>
              </tr>
            </tbody>
          </table>
        </div>
      </div>
      <div class="event-list">
        <h4>异常事件列表</h4>
        <table>
          <thead>
            <tr>
              <th @click="sortAbnormalEvents('device_name')">设备名称</th>
              <th @click="sortAbnormalEvents('abnormal_voltage')">异常电压</th>
              <th>常规电压</th>
              <th>异常时间</th>
              <th>异常级别</th>
            </tr>
          </thead>
          <tbody>
            <tr v-if="!abnormalEvents.length">
              <td colspan="5" class="no-events">今日暂无异常事件</td>
            </tr>
            <tr v-else v-for="event in abnormalEvents" :key="event.device_id">
              <td>{{ event.device_name }}</td>
              <td>{{ event.abnormal_voltage }}V</td>
              <td>{{ event.normal_voltage }}V</td>
              <td>{{ new Date(event.timestamp).toLocaleString() }}</td>
              <td>{{ event.outlier_level }}</td>
            </tr>
          </tbody>
        </table>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, defineProps, onMounted, watch, computed } from "vue";
import { areaRankingService } from "@/services";
import 'element-plus/theme-chalk/index.css';
// 在脚本部分导入服务
import { abnormalHistoryService } from "@/services";

// 添加异常事件数据的响应性引用
const abnormalEvents = ref([]);
import { ElTabs, ElTabPane, ElSelect, ElOption } from 'element-plus';

const props = defineProps(["areaId"]);
const allDeviceTypes = ref(new Set());
const deviceTypeCounts = ref({});
const selectedMoldCode = ref("");
const activeTab = ref("daily");
const noData = ref(true); // 初始值设为 true，直到数据加载完成
const dailyRankingData = ref([]);
const weeklyRankingData = ref([]);
const monthlyRankingData = ref([]);

const sortKey = ref('');
const sortOrder = ref('asc');  // 'asc' 或 'desc'

const fetchData = async (area_id) => {
  const responses = await Promise.all([
    areaRankingService.getDayRankingService(area_id),
    areaRankingService.getWeekRankingService(area_id),
    areaRankingService.getMonthRankingService(area_id),
  ]);
  dailyRankingData.value = processRankingData(responses[0].data);
  weeklyRankingData.value = processRankingData(responses[1].data);
  monthlyRankingData.value = processRankingData(responses[2].data);
  deviceTypeCounts.value = responses[2].data.probe_mold_code_count;
  console.log("deviceTypeCounts:", responses[2].data.probe_mold_code_count);
  if (dailyRankingData.value.length || weeklyRankingData.value.length || monthlyRankingData.value.length) {
    noData.value = true;
  }
  const abnormalResponse = await abnormalHistoryService.getRegionService(area_id);
  // 合并所有设备的异常数据到一个数组中
  abnormalEvents.value = Object.values(abnormalResponse.data).flat();
  console.log("abnormalEvents:", abnormalEvents.value);
  
};

const processRankingData = (data) => {
  const processedData = Object.values(data.top_10 || {}).sort(
    (a, b) => b.total_ele_quantity - a.total_ele_quantity
  );
  processedData.forEach((item) => {
    allDeviceTypes.value.add(item.probe_mold_code);
  });
  return processedData;
};

watch(
  () => props.areaId,
  (newAreaId) => {
    if (newAreaId) {
      fetchData(newAreaId);
    }
  }
);

onMounted(() => {
  if (props.areaId) {
    fetchData(props.areaId);
  }
});

const filteredRankingData = computed(() => {
  let data;
  switch (activeTab.value) {
    case "daily":
      data = dailyRankingData.value;
      break;
    case "weekly":
      data = weeklyRankingData.value;
      break;
    case "monthly":
      data = monthlyRankingData.value;
      break;
    default:
      data = [];
  }
  if (selectedMoldCode.value) {
    console.log("filteredRankingData:", data);
    data = data.filter(
      (item) => item.probe_mold_code === Number(selectedMoldCode.value) 
    );
    console.log("filteredRankingData:", data);
  }
  return data;
});

// Helper function to get the active tab label

const sortAbnormalEvents = (key) => {
  abnormalEvents.value.sort((a, b) => {
    if (a[key] < b[key]) {
      return -1;
    }
    if (a[key] > b[key]) {
      return 1;
    }
    return 0;
  });
};
</script>

<style scoped>
@import url('https://fonts.googleapis.com/css2?family=Roboto:wght@300;400;500;700&display=swap');

.abnormal {
  font-size: 60px; /* 设置文字大小 */
  color: white; /* 设置文字颜色 */
  font-weight: bolder; /* 设置文字宽度 */
  text-align: center; /* 设置文字居中 */
}

::v-deep .el-tabs__item {
  color: white;
}

.data-ranking {
  flex-shrink: 0;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
  font-family: 'Roboto', sans-serif;
  background-color: #1a1a2e;
  color: #fff;
}

.controls {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.custom-tabs {
  background-color: #27293d;
  border-radius: 8px;
  color: #fff;
}

.custom-tabs .el-tabs__item {
  color: #ffffff; /* 选项卡的颜色 */
}

.custom-tabs .el-tab-pane {
  color: #ffffff; /* 选项卡的颜色 */
}

.custom-select {
  background-color: #27293d;
  color: #fff;
  border: none;
  width: 200px;
}

.content-row {
  display: flex;
  justify-content: space-between;
  width: 100%;
  height: 220px;
}

.ranking-chart {
  flex: 1;
  border-radius: 8px;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
  background-color: #2a2c42;
  min-width: 0;
}

.ranking-list {
  max-height: 180px;
  overflow-y: auto;
}

.ranking-list table {
  width: 100%;
  border-collapse: collapse;
}

.ranking-list th,
.ranking-list td {
  padding: 8px 12px;
  text-align: left;
  background-color: #313552;
  color: #fff;
}

.ranking-list th {
  background-color: #3e4166;
  font-weight: bold;
}

.ranking-list tr:hover {
  background-color: #0015ff;
}

.el-tabs {
  color: #fff;
  width: 360px;
}

.event-list {
  flex: 0 0 60%;
  margin-left: 20px;
  border-radius: 8px;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
  background-color: #2a2c42;
  height: 210px;
  text-align: center;
  overflow-y: auto;
}


.event-list h4 {
  font-size: 1.5em;
  color: #ffffff;
}

.event-list p {
  font-size: 1em;
  color: #fff;
}

.event-list table {
  width: 100%;
  border-collapse: collapse;
  margin-top: 10px;
}

.event-list th,
.event-list td {
  padding: 12px;
  border: 1px solid #3e4166;
  text-align: left;
  color: #fff;
}.event-list th {
  background-color: #464a72;
}

.event-list tr:nth-child(even) {
  background-color: #3e4166;
}

.event-list tr:hover {
  background-color: #464a72;
}
.skeleton {
  background-color: #3e4166;
  opacity: 0.5;
  animation: pulse 1.5s infinite;
}

@keyframes pulse {
  0% {
    opacity: 0.5;
  }
  50% {
    opacity: 0.2;
  }
  100% {
    opacity: 0.5;
  }
}
</style>